import time

from app.extensions import db


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, unique=True, nullable=False)
    user_token = db.Column(db.String(120))
    user_info = db.Column(db.JSON)
    create_time = db.Column(db.Integer, comment="创建时间")
    update_time = db.Column(db.Integer, comment="更新时间")

    @classmethod
    def save_data(cls, data, user_token):
        old_obj = cls.query.filter_by(user_id=data['id']).first()
        obj = old_obj if old_obj else cls()
        obj.user_id = data["id"]
        obj.user_info = data
        obj.user_token = user_token
        obj.update_time = int(time.time())

        if not old_obj:
            obj.create_time = int(time.time())
            db.session.add(obj)

        db.session.commit()

    @classmethod
    def get_by_token(cls, user_token):
        return cls.query.filter_by(user_token=user_token).first()
